package com.Test;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Enumeration;

/**
 * Created by Administrator on 2016/3/27.
 */
@WebServlet(name = "LoginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String username = request.getParameter("username");
            String password = request.getParameter("password");
         Enumeration params = this.getInitParameterNames(); //所有的初始化参数名称
        while(params.hasMoreElements()){ //遍历所有的初始化参数
            String usernameP = (String)params.nextElement(); //取参数名
            String passwordP =  getInitParameter(usernameP); //取参数值
            if(usernameP.equals(username)){
                if(passwordP.equals(password)){
                    request.getRequestDispatcher("../index.jsp").forward(request,response);
                    return;
                }else{
                    response.setCharacterEncoding("UTF-8");
                    request.setCharacterEncoding("UTF-8");
                    response.setContentType("text/html");
                    PrintWriter out = response.getWriter();
                    out.print("密码错误");
                    out.print("剩余秒数:3");
                    response.setHeader("Refresh","3; URL=http://localhost:8080/JavaWeb/login.jsp");
                    out.flush();
                    out.close();
                    return;
                }
            }else{
                this.doGet(request,response);
            }
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html");
        response.setHeader("Refresh","1; URL=http://localhost:8080/JavaWeb/login.jsp");
        PrintWriter out = response.getWriter();
        Date date = new Date();
        out.print("用户不存在");
        out.print(date);
        out.flush();
        out.close();
    }
}
